/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package makao;

import javax.swing.JLabel;

public class Clock implements Runnable
{
    private static final int SEC = 180;
    
    private Thread runner = null;
    private JLabel timeLabel;
    private Boolean check = true;
    private String time;
    private int minutes = SEC / 60;
    private int seconds = SEC % 60;

    public Clock(JLabel timeLabel)
    {
        this.timeLabel = timeLabel;
    }

    public void setTime()
    {
        
        if( seconds < 0 )
        {
            minutes--;
            seconds = 59;
        }
        
        time = zero(minutes) + " : " + zero(seconds);
        timeLabel.setText(time);
        
        if( seconds == 0 && minutes == 0 )
        {
            clearTime();
            check = false;
        }
        
        seconds--;
    }

    private String zero(int num)
    {
        String number = (num < 10) ? ("0" + num) : ("" + num);
        return number;

    }

    public void stopTime()
    {
        check = false;
        clearTime();
    }

    public void clearTime()
    {
        minutes = SEC / 60;
        seconds = SEC % 60;
        timeLabel.setText("-- : --");
    }

    public void run()
    {
        while (check)
        {
            setTime();

            try
            {
                Thread.sleep(1000);
            } catch (InterruptedException e)
            {
                System.out.println("Thread failed");
            }

        }
    }

    public void startThread()
    {
        if ( runner == null || !runner.isAlive() )
        {
            runner = new Thread(this);
        
            check = true;
            runner.start();
        }
    }
}
